import {
  query,
  add,
  remove,
  edit,
  queryResources,
  queryLogs,
  queryOneUsergroup,
} from '@/services/level_annual_billings';
import moment from 'moment';
import { todayLastSecond } from '@/utils/utils.js';
import sortBy from 'lodash/sortBy';
import filter from 'lodash/filter'

export default {
  namespace: 'level_annual_billings1',
  state: {
    pageLoaded: false,
    tableY: 0,
    data: [],
    originData: [],
    scrollData: { x: 0, y: 0 },
    selectedRowKeys: [0],
    searchParams: {
      region_ids: [],
      region_names: [],
      year: moment(new Date()).format('YYYY'),
      start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD').format('YYYY-MM-DD'),
      end_date: moment(new Date()).format('YYYY-MM-DD'),
      page: 1,
      per_page: 20,
      filter:0
    },
    meta: { total: 50, per_page: 50, current_page: 1 },
    summary: [],
    loading: true,
    detail: {
      pageLoaded: false,
      isDetail: false,
    },

  },
  effects: {
    * changeIsDetail({ payload, callback }, { call, put, select }) {
      console.log('changeIsDetail');
      const { detail } = yield select(state => state.staff_report);
      yield put({
        type: 'changeDetail',
        payload: {
          ...detail,
          isDetail: !detail.isDetail,
          detailId: payload.id,
        },
      });
    },
    * reset({ payload, callback }, { call, put }) {
      console.log('reset=============');
      yield put({
        type: 'resetData',
        payload: payload,
      });
      if (callback) callback();
    },
    * changeTableY({ payload, callback }, { call, put }) {
      const tableY = document.body.offsetHeight -
        document.querySelector('.meter-table').getBoundingClientRect().top - 70;
      yield put({
        type: 'saveTableY',
        payload: tableY,
      });
    },
    * changeSearchParams({ payload, callback }, { call, put }) {
      console.log('changeSearchParams');
      yield put({
        type: 'saveSearchParams',
        payload: payload,
      });
    },
    * changeLoaded({ payload, callback }, { call, put }) {
      yield put({
        type: 'changePageLoaded',
        payload: true,
      });
    },
    * changeScroll({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeScrollData',
        payload: payload,
      });
    },
    * selectRow({ payload, callback }, { call, put, select }) {
      const { selectedRowKeys } = yield select(state => state.level_annual_billings1);
      if (selectedRowKeys.indexOf(payload.id) >= 0) {
        selectedRowKeys.splice(selectedRowKeys.indexOf(payload.id), 1);
      } else {
        selectedRowKeys.push(payload.id);
      }
      yield put({
        type: 'saveSelectRow',
        payload: selectedRowKeys,
      });
    },
    * fetch({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const state = yield select(state => state.level_annual_billings1);//获取state中的数据
      payload = payload || state.searchParams;
      console.log('payload', payload);
      const response = yield call(query, payload);
      if (response.status === 200) {
        let parseData = [];
        response.data.data = sortBy(response.data.data, function(o) {
          return -o.total_account_count;
        });
        response.data.data = filter( response.data.data, function(o) {
          if(payload.filter===2){
            return o.level_two_account_count>0
          }else if(payload.filter===3){
            return o.level_three_account_count>0
          }
          return  true
        });
        for (let i = 0; i < response.data.data.length; i++) {

          parseData.push({
              index: i + 1,
              region_name: response.data.data[i].region_name,
              region_id: response.data.data[i].region_id,
              count: response.data.data[i].level_one_account_count,
              level_name: '一阶',
              myId: String(Math.random()),
            }, {
              region_name: response.data.data[i].region_name,
              region_id: response.data.data[i].region_id,
              count: response.data.data[i].level_two_account_count,
              level_name: '二阶',
              myId: String(Math.random()),
            }, {
              region_name: response.data.data[i].region_name,
              region_id: response.data.data[i].region_id,
              count: response.data.data[i].level_three_account_count,
              level_name: '三阶',
              myId: String(Math.random()),
            }, {
              region_name: response.data.data[i].region_name,
              region_id: response.data.data[i].region_id,
              count: response.data.data[i].total_account_count,
              level_name: '合计',
              myId: String(Math.random()),
            },
          );
        }
        console.log('parseData', parseData);
        yield put({
          type: 'save',
          payload: parseData,
        });
        yield put({
          type: 'saveOriginData',
          payload: response.data.data,
        });
        yield put({
          type: 'saveSearchParams',
          payload: payload,
        });
        yield put({
          type: 'changeLoading',
          payload: false,
        });
        if (callback) callback();
      }

    },
    * add({ payload, callback }, { call, put }) {
      const response = yield call(add, payload);

      console.log(response);
      if (response.status === 200) {
        if (callback) callback();
      } else {
      }
    },
    * edit({ payload, callback }, { call, put }) {
      console.log('edit');
      const response = yield call(edit, payload);
      console.log(response);
      if (response.status === 200) {
        if (callback) callback();
      }
    },
    * changeSelectRow({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'saveSelectRow',
        payload: payload,
      });
    },
    * remove({ payload, callback }, { call, put }) {
      const response = yield call(remove, payload);
      if (response.status === 200) {
        if (callback) callback();
      }
    },
    * fetchDetail({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const { detail } = yield select(state => state.staff_report);//获取state中的数据
      console.log('detail', detail);
      const response = yield call(queryResources, {
        id: detail.detailId,
      });
      payload = {
        ...detail.searchParams2,
        ...payload,
      };
      console.log('payload', payload);
      const response2 = yield call(queryLogs, {
        id: detail.detailId,
        ...payload,
      });
      if (response.status === 200 && response2.status === 200) {
        yield put({
          type: 'saveResources',
          payload: response.data,
        });
        yield put({
          type: 'saveLogs',
          payload: response2.data,
        });
        yield put({
          type: 'saveDetailSearchParams',
          payload: payload,
        });
        yield put({
          type: 'changeLoading',
          payload: false,
        });
        if (callback) callback();
      }

    },
    * resetDetail({ payload, callback }, { call, put, select }) {
      console.log('reset detail', payload);
      yield put({
        type: 'resetDetailData',
        payload: payload,
      });
      if (callback) callback();
    },
    * changeDetailLoaded({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeDetailPageLoaded',
        payload: true,
      });
    },
    * changeDetailActive({ payload, callback }, { call, put }) {
      console.log(payload);
      yield put({
        type: 'changeDetailTabActive',
        payload: payload,
      });
      if (callback) callback();
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    saveOriginData(state, action) {
      return {
        ...state,
        originData: action.payload,
      };
    },
    saveTableY(state, action) {
      return {
        ...state,
        tableY: action.payload,
      };
    },
    saveOneRecord(state, action) {
      return {
        ...state,
        editRecord: action.payload,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
    changePageLoaded(state, action) {
      return {
        ...state,
        pageLoaded: action.payload,
      };
    },
    changeScrollData(state, action) {
      return {
        ...state,
        scrollData: action.payload,
      };
    },
    saveSearchParams(state, action) {
      return {
        ...state,
        searchParams: {
          ...state.searchParams,
          ...action.payload,
        },
      };
    },
    resetData(state, action) {
      return {
        pageLoaded: action.payload,
        data: [],
        originData: [],
        scrollData: { x: 0, y: 0 },
        selectedRowKeys: [],
        tableY: state.tableY,
        searchParams: {
          region_ids: [],
          region_names: [],
          year: moment(new Date()).format('YYYY'),
          start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD').format('YYYY-MM-DD'),
          end_date: moment(new Date()).format('YYYY-MM-DD'),
          page: 1,
          per_page: 20,
          filter:0
        },
        meta: { total: 0, per_page: 0, current_page: 1 },
        loading: true,
        editRecord: {},
        summary: [],
        detail: {
          pageLoaded: false,
          isDetail: false,
          detailId: '',
          data1: [],
          activeKey: '1',
          data2: [],
          searchParams2: {
            start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
            end_date: todayLastSecond(),
            status: '0',
            page: 1,
            per_page: 20,
          },
          meta2: { total: 0, per_page: 0, current_page: 1 },
        },
      };
    },
    resetDetailData(state, action) {
      console.log('state', state);
      return {
        ...state,
        detail: {
          ...state.detail,
          pageLoaded: action.payload,
          data1: [],
          data2: [],
          searchParams2: {
            start_date: moment(new Date().getFullYear() + '-' + (parseInt(new Date().getMonth()) + 1) + '-' + '01', 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
            end_date: todayLastSecond(),
            status: '0',
            page: 1,
            per_page: 20,
          },
          meta2: { total: 0, per_page: 0, current_page: 1 },
        },

      };
    },
    changeDetailPageLoaded(state, action) {
      const detail = { ...state.detail };
      return {
        ...state,
        detail: {
          ...detail,
          pageLoaded: action.payload,
        },

      };
    },
    saveResources(state, action) {
      return {
        ...state,
        detail: {
          ...state.detail,
          data1: action.payload.data,
        },
      };
    },
    saveLogs(state, action) {
      return {
        ...state,
        detail: {
          ...state.detail,
          data2: action.payload.data,
          meta2: action.payload.meta,
        },
      };
    },
    saveSelectRow(state, action) {
      return {
        ...state,
        selectedRowKeys: action.payload,
      };
    },
    changeDetail(state, action) {
      return {
        ...state,
        detail: action.payload,
      };
    },
    changeDetailTabActive(state, action) {
      return {
        ...state,
        detail: {
          ...state.detail,
          activeKey: action.payload,
        },
      };
    },
    saveDetailSearchParams(state, action) {
      return {
        ...state,
        detail: {
          ...state.detail,
          searchParams2: action.payload,
        },

      };
    },
  },

};
